<template>
  <ZDialog width='578px'
           :title="$t('paywall.cypp')"
           :minHeight="631"
           :footer="false"
           lock-scroll
           destroy-on-close
           append-to-body
           customClass="b-dialog-pay relative"
           @open="open"
           v-model="currentValue">
    <div class="user-setting flex-1 flex flex-col relative overflow-auto"
         v-loading="loading">
      <div class="user-setting-item">

        <ConfigMessage/>
      </div>

      <div class="user-setting-item">
        <Seats name="Purchased users"
               :total="total === 'Infinity' ? 'Unlimited': Number(total)" />
        <Seats name="Available Users"
               :total="idle === 'Infinity' ? 'Unlimited': Number(total) -  this.paidAccounts.length" />
        <Seats name="Assigned users"
               :total="use === 'Infinity' ? 'Unlimited': this.paidAccounts.length" />
      </div>
      <div class="user-setting-item">
        <paidAccounts v-model="paidAccounts"
                      :users="users"
                      :limit="total"
                      :disabled="disabledPaid"
                      height="337px" />
      </div>
      <div class="user-setting__bottom flex-1 flex flex-col justify-end items-end">
        <el-button size="small"
                   type="primary"
                   @click="save">{{$t('paywall.save')}}</el-button>
      </div>
    </div>
  </ZDialog>
</template>

<script>
import ZDialog from '@/components/storybook/z-dialog'
import paidAccounts from '@/components/storybook/b-dialog-pay/paid-accounts'
import Seats from '@/components/storybook/b-dialog-pay/seats'
import ConfigMessage from '@/components/storybook/b-dialog-pay/config-message'
import config from '@/utils/config'
import { getAppUsers } from '@/components/storybook/utilties/chargebee'
import { get } from 'lodash'
export default {
  name: 'botUser',
  props: {
    value: [String, Boolean],
  },
  components: {
    ZDialog,
    paidAccounts,
    Seats,
    ConfigMessage
  },
  data () {
    return {
      loading: false,
      paidAccounts: [],
      // all users
      users: [],

      idle: '0',
      total: '0',
      use: '0'
    }
  },
  computed: {
    currentValue: {
      get () {
        return !!this.value
      },
      set (val) {
        this.$emit('input', val || null)
      }
    },
    disabledPaid () {
      const total = this.total === 'Infinity' ? Infinity : Number(this.total)
      return this.paidAccounts.length === total
    },
    appId () {
      return this.$route.query.appId
    }
  },
  watch: {
    everUsers (value) {
      if (value.length) {
        this.freeAccounts = value.filter(account => account.accountType === 1).map(i => {
          const user = this.users.find(u => u.id === i.userId)
          return { ...user }
        })
        if (this.total !== '0') {
          this.paidAccounts = value.filter(account => account.accountType === 2).map(i => {
            const user = this.users.find(u => u.id === i.userId)
            return { ...user }
          })
        }
      }
    }
  },
  methods: {
    open () {
      this.init()
    },
    async init () {
      try {
        this.loading = true
        await this.getUsers()
        await this.getBotUserList()
      } catch (error) {

      } finally {
        this.loading = false
      }
    },
    async getBotUserList () {
      const { data } = await this.$interface.pay.getBotUserList()
      if (data) {
        if (data.data && data.data.userIds) {
          this.paidAccounts = data.data.userIds.map(item => {
            return this._.find(this.users, { id: item })
          })
        }
        this.idle = data.data.idle
        this.total = data.data.total
        this.use = data.data.use
      }
    },
    async getUsers () {
      const { getWorkScheduledUserListApi } = this.$interface.schedule
      const params = {
        status: 1,
        regSource: '1'
      }
      let { data: response } = await getWorkScheduledUserListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      this.users = this._.filter(response.data, (item) => {
        return this._.intersection(config.freeUserRole, item.roleIds).length === 0
      })
      return this.users
    },
    refresh () {
      this.$store.state.contentIsNeedRefresh = true
      this.$store.state.app.contentIsNeedRefreshCache = true
      this.$nextTick(() => {
        this.$store.state.contentIsNeedRefresh = false
      })
    },
    async save () {
      try {
        this.loading = true
        const params = {
          userIds: this.paidAccounts.map(item => {
            return item.id
          })
        }
        const { saveBotUserList } = this.$interface.pay
        await saveBotUserList(params)
        this.currentValue = false
        this.$message.success(this.$t('success'))
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss">
.b-dialog-pay {
  & > .el-dialog__body {
    padding: 0;
  }
}
.user-setting {
  overflow: hidden;
  &-item {
    margin-bottom: 16px;
    &--name {
      font-size: 14px;
      color: #404040;
      font-weight: 600;
    }
  }
  &__footer {
  }
}
</style>
